import 'dart:async';

//import 'package:flutter_blue/flutter_blue.dart';
import 'dart:io';
import 'dart:ui';
import 'package:flutter/material.dart';
import 'dart:convert';
import 'dart:typed_data';
import 'dart:ui';
import 'package:flutter/material.dart';
import 'package:flutter_bluetooth_serial/flutter_bluetooth_serial.dart';
import 'package:magic_car/common/global.dart';
import 'package:magic_car/user/agenterror.dart';
import 'package:magic_car/util/HttpHelper.dart';
import 'package:shared_preferences/shared_preferences.dart';

import 'package:toast/toast.dart';
import 'package:magic_car/main.dart';
// import 'package:amap_location/amap_location.dart';
import 'package:permission_handler/permission_handler.dart';

//import 'package:flutter/bluetooth/bluetooth.dart';
class BluePages extends StatefulWidget {
  BluePages({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => new _MyHomePageState();
}

class _MyHomePageState extends State<BluePages> {
  List formList = [];
  List<BluetoothDevice> devices = [];
  bool startscan = false;
  FlutterBluetoothSerial flutterBlue = FlutterBluetoothSerial.instance;
  BluetoothConnection connection;
  // FlutterBlue flutterBlue = FlutterBlue.instance;
  BluetoothDevice device;
  String _messageBuffer = '';
  bool isconnect = false;
  String code_string ='' ;
  int deviceindex;
  // BluetoothCharacteristic cread;
  // BluetoothCharacteristic cwrite;

  String sendCode = "ATZ";
  String sendModel = "03";
  initState() {
    super.initState();
    // change();
    // startLcoations();
    // getLocationInfo();
  }

  Widget buildcontent() {
    List<Widget> tiles = [];
    Widget content;
    if (formList.length > 0) {
      for (var i = 0; i < formList.length; i++) {
        var item = formList[i];
        tiles.add(Padding(
            padding: new EdgeInsets.fromLTRB(15, 15, 15, 0),
            child: Container(
              width: double.infinity - 20,
              decoration: new BoxDecoration(
                color: Colors.white,
              ),
              child: new GestureDetector(
                  behavior: HitTestBehavior.opaque,
                  onTap: () {
                    device = devices[i];
                    deviceindex = i;
                    //startConnecting();
                    // print('1212');
                    // device = devices[i];
                    if (isconnect == true) {
                      // startConnecting(0);
                      sendCode = "ATZ";
                      writedata(sendCode);
                    } else
                      startConnecting(1,i);
                    // startconnetc(i);
                  },
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.start,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      Padding(
                        padding: new EdgeInsets.fromLTRB(20, 15, 20, 10),
                        child: Column(
                          children: <Widget>[
                            Text(item["name"]),
                            Text(item['value'])
                          ],
                        ),
                      ),
                    ],
                  )),
            )));
      }
    }
    content = new Column(
        children: tiles //重点在这里，因为用编辑器写Column生成的children后面会跟一个<Widget>[]，
        //此时如果我们直接把生成的tiles放在<Widget>[]中是会报一个类型不匹配的错误，把<Widget>[]删了就可以了
        );
    return content;
  }

  startLcoations() async {
    print('开始定位');

   if(await Permission.location.request().isGranted) {
      // 干你该干的事
    }
  }

  change() {
    Map<String, String> map = new Map();
    map['str'] = "ATZ";

    String api = HttpHelper.API_ChangeByte;

    HttpHelper.post(api, (data) async {
      if (data != null) {
        print(data);
        Toast.show(data["msg"], context);

        // pref.setStringList('userinfo', data["info"]);

      }
    }, params: map);
  }

  //发送数据
  writedata(str) async {
    List<int> b = Utf8Codec().encode(str + '\r');
    print('写入值$b');
    print('写入值转换：$str');

    connection.output.add(b);
    //cwrite.flush();
  }

  int num = 0;
  // startconnetc(index) async {
  //   const timeout = const Duration(seconds: 5);
  //   flutterBlue.stopScan();
  //   await device.disconnect();
  //   await device.connect();

  //   setState(() {});

  //   List<BluetoothService> services = await device.discoverServices();
  //   services.forEach((service) async {
  //     // do something with service
  //     var characteristics = service.characteristics;
  //     for (BluetoothCharacteristic c in characteristics) {
  //       print('cuuid-------');
  //       print(c.uuid.toString());

  //       //List<int> b=Utf8Codec().encode('ATSP'+num.toString());
  //       //ATZ
  //       List<int> b = Utf8Codec().encode('ATZ\r\n');
  //       num = 0;
  //       // if(c.uuid.toString()==GattAttributes.BLE_SPP_SERVICE_READ){

  //       // }

  //       //00002a00-0000-1000-8000-00805f9b34fb
  //       //0000fff2-0000-1000-8000-00805f9b34fb
  //       if (c.uuid.toString() == "00002a01-0000-1000-8000-00805f9b34fb") {
  //         cwrite = c;
  //         writedata(sendCode);
  //       }
  //       //0000fff1-0000-1000-8000-00805f9b34fb
  //       //00002a01-0000-1000-8000-00805f9b34fb
  //       if (c.uuid.toString() == "00002a00-0000-1000-8000-00805f9b34fb") {
  //         Timer(timeout, () async {
  //           await c.setNotifyValue(true);
  //         });

  //         c.value.listen((value) async {
  //           var item = formList[index];

  //           if (value.length == 0) {
  //           } else {
  //             String recieve = Utf8Codec().decode(value).toString().trim();
  //             print('接收值$value');
  //             print('接收值转换结果$recieve');
  //             item['value'] = '发送指令$sendCode' + '接收值$recieve';

  //             if (recieve.contains("41")) {
  //               // if (recieve.contains('OK')) {
  //               print('协议走通，协议为$num');

  //               sendCode = '03';

  //               //  sendCode = "$sendCode";
  //               writedata(sendCode);
  //             }

  //             if (sendCode == "ATZ") {
  //               if (recieve[0] == "E") {
  //                 sendCode = "ATL0";
  //                 writedata(sendCode);
  //               } else {
  //                 writedata(sendCode);
  //               }
  //             } else if (sendCode == "ATL0") {
  //               if (recieve[0] == "A") {
  //                 sendCode = "ATE1";
  //                 writedata(sendCode);
  //               } else {
  //                 writedata(sendCode);
  //               }
  //             } else if (sendCode == "ATE1") {
  //               if (recieve[2] == "E") {
  //                 sendCode = "ATH0";
  //                 writedata(sendCode);
  //               } else {
  //                 writedata(sendCode);
  //               }
  //             } else if (sendCode == "ATH0") {
  //               if (recieve[2] == "H") {
  //                 sendCode = "ATSP0";
  //                 writedata(sendCode);
  //               } else {
  //                 writedata(sendCode);
  //               }
  //             } else if (sendCode == "ATSP" + num.toString()) {
  //               if (recieve.contains('OK') && recieve.contains('ATSP')) {
  //                 sendCode = "0100";
  //                 writedata(sendCode);
  //               } else {
  //                 // if (num < 9) {
  //                 //   num++;
  //                 // } else {
  //                 //   num = 0;
  //                 // }
  //                 // sendCode = "ATSP" + num.toString();
  //                 // writedata(sendCode);
  //               }
  //             } else if (sendCode == "0100") {
  //               if (recieve.contains("41")) {
  //                 // if (recieve.contains('OK')) {
  //                 print('协议走通，协议为$num');

  //                 sendCode = '03';

  //                 //  sendCode = "$sendCode";
  //                 writedata(sendCode);
  //               } else {
  //                 if (num < 9) {
  //                   num++;
  //                 } else {
  //                   num = 0;
  //                 }
  //                 sendCode = "ATSP" + num.toString();
  //                 writedata(sendCode);
  //               }
  //             } else if (sendCode == "0101") {
  //               print('------故障代码个数返回值-------$recieve');
  //             } else if (sendCode.contains('03')) {
  //               print('------故障代码返回值-------$recieve');
  //             } else if (sendCode == '04') {
  //               print('------清楚故障代码返回值-------$recieve');
  //             } else if (sendCode == '07') {
  //               print('------07故障代码返回值-------$recieve');
  //             } else if (sendCode == "01") {
  //               print('------故障代码返回值01-------$recieve');
  //             } else if (sendCode == "0120") {
  //               //pid20-40
  //               if (recieve.contains("41")) {
  //                 sendCode = "0140";
  //                 writedata(sendCode);
  //               } else {
  //                 // //继续查找40断的pid是否支持
  //                 // sendCode = "0140";
  //                 // writedata(sendCode);
  //               }
  //             } else if (sendCode == "0140") {
  //               if (recieve.contains("41")) {
  //                 sendCode = "0160";
  //               }
  //               writedata(sendCode);
  //             } else if (sendCode == "0160") {
  //               if (recieve.contains("41")) {
  //                 sendCode = "010D";
  //               }
  //               writedata(sendCode);
  //             } else if (sendCode == "010D") {
  //               print('010D 返回数据$recieve');
  //               if (recieve.contains("41")) {
  //                 sendCode = "03";
  //               }
  //               writedata(sendCode);
  //             }

  //             setState(() {
  //               formList = formList;
  //             });
  //           }
  //           // print('88888888888888888888888$value');
  //         });
  //       }
  //     }
  //   });
  // }
//
  String recieve = "";
  List<int> bytedata = [];
  startConnecting(type,index) async {
    if (type == 1) {
      if (device.isBonded) {
        //如果已连接，断开连接
        await flutterBlue.removeDeviceBondWithAddress(device.address);
      }

      connection = await BluetoothConnection.toAddress(device.address); //连接设备
      setState(() {
        isconnect = true;
      });
    }
    writedata(sendCode);

    await connection.output.allSent;
    //connection.input.listen(_onDataReceived).onDone(() {});

    connection.input.listen((Uint8List datas) {
      print('接收字节$datas');
      String recieve = Utf8Codec().decode(datas).toString().trim();
      if (!recieve.contains('>')) {
        //结束
        for (int i = 0; i < datas.length; i++) {
          bytedata.add(datas[i]);
        }
        return;
      } else {
        for (int i = 0; i < datas.length; i++) {
          bytedata.add(datas[i]);
        }
         recieve = Utf8Codec().decode(bytedata).toString().trim();
        bytedata = [];//清空数组
      }
      
      print('接收值$recieve');
      if (!recieve.contains('>') && sendCode != "0100") {
        //接收值，结束标志
        return; //知道接收到结束符才处理信息
      }

      if (sendCode == "ATZ") {
        if (recieve[0] == "E") {
          print('ATZ成功');
          sendCode = "ATL0";
          writedata(sendCode);
        } else {
          writedata(sendCode);
        }
      } else if (sendCode == "ATL0") {
        if (recieve[0] == "A") {
          print('ATL0成功');
          print(recieve[4]);
          sendCode = "ATE1";
          writedata(sendCode);
        } else {
          writedata(sendCode);
        }
      } else if (sendCode == "ATE1") {
        if (recieve[2] == "E") {
          print('ATE1成功');
          sendCode = "ATH0";
          writedata(sendCode);
        } else {
          writedata(sendCode);
        }
      } else if (sendCode == "ATH0") {
        if (recieve[2] == "H") {
          print('ATH0成功');
          sendCode = "ATSP6";
          num = 6;
          writedata(sendCode);
        } else {
          writedata(sendCode);
        }
      } else if (sendCode == "ATSP" + num.toString()) {
        if (recieve.contains('ATSP') && recieve.contains('OK')) {
          sendCode = "0100";
          writedata(sendCode);
        } else {
          if (num < 9) {
            num++;
          } else {
            num = 0;
          }
          sendCode = "ATSP" + num.toString();
          writedata(sendCode);
        }
      }
      // else if (sendCode == "0100") {
      //   if (recieve.contains('41 00')) {
      //     sendCode = "03";
      //     writedata(sendCode);
      //   }
      // }
      // else if (sendCode == "03") {
      //   print('故障代码$recieve');
      // }
      if (recieve.contains('41 00')) {
        sendCode = "03";
        writedata(sendCode);
      }
      //recieve.contains('43')
      if (recieve.contains('43')&&sendCode=="03") {
        // if (recieve.contains('>')) {
        //   //结束标志
        //   for (int i = 0; i < datas.length; i++) {
        //     bytedata.add(datas[i]);
        //   }
        //   handleproblem();
        // } else {
        //   //bytedata = datas;
        //   for (int i = 0; i < datas.length; i++) {
        //     bytedata.add(datas[i]);
        //   }
        //   //recieve = Utf8Codec().decode(bytedata).toString().trim();
        // }
        print('检测到故障代码$recieve');
        var items = {'name': '接收的故障码', 'value': recieve};
        formList.add(items);
        setState(() {
          formList = formList;
        });
        // Toast.show('检测到故障代码$recieve', context);
        List temp_arr_str = recieve.split(' ');
        print(temp_arr_str[0].toString());
        print(temp_arr_str[1].toString());
        String codes = 'P';
        for (int i = 0; i < temp_arr_str.length; i++) {
          if(temp_arr_str[i]=="01"){
             codes = codes + temp_arr_str[i]+temp_arr_str[i+1];
            codes = codes + ',P';
          }
          // codes = codes + temp_arr_str[i];
          // if (i % 2 != 0) {
          //   codes = codes + ',P';
          // }
        }
        print('组装之后的故障码$codes');
        setState(() {
           code_string = codes;
        });
        var item = formList[index];
        item['value'] = '接收的故障码：' + code_string;
        setState(() {
          formList = formList;
        });
        getcodedesc();
      }
    }).onDone(() {
      print('Disconnected by remote request');
    });
    //List<BluetoothService> services = await device.discoverServices();
  }
  getcodedesc() {
    formList[deviceindex]['value'] = '接收故障码：' + code_string;
    Map<String, String> map = new Map();
    map['code'] = code_string;

    String api = HttpHelper.API_GetTroubleCode;

    HttpHelper.post(api, (data) async {
      if (data != null) {
        print(data);
        Toast.show(data["msg"], context);
        if (data['code'].toString() == "1") {
          var str = '';
          for (int i = 0; i < data['info'].length; i++) {
            print(data['info'][i]['code']);
            str = str +
                '故障码：' +
                data['info'][i]['code'] +
                ',故障描述：' +
                data['info'][i]['descrble'] +
                '\r';
          }
          formList[deviceindex]['value'] = str;
          setState(() {
            formList = formList;
          });
        }

        // pref.setStringList('userinfo', data["info"]);

      }
    }, params: map);
  }
  //处理故障码
  handleproblem() {
    recieve = Utf8Codec().decode(bytedata).toString().trim();
    print('检测到故障代码$recieve');
    var items = {'name': '接收的故障码', 'value': recieve};
    formList.add(items);
    setState(() {
      formList = formList;
    });
    // Toast.show('检测到故障代码$recieve', context);
    List temp_arr_str = recieve.split(' ');
    print(temp_arr_str[0].toString());
    print(temp_arr_str[1].toString());
    String codes = 'P';
    for (int i = 2; i < temp_arr_str.length; i++) {
      codes = codes + temp_arr_str[i];
      if (i % 2 != 0) {
        codes = codes + ',P';
      }
    }
    print('组装之后的故障码$codes');
    setState(() {
      // code_string = codes;
    });
  }

  void _onDataReceived(Uint8List data) {
    // Allocate buffer for parsed data
    int backspacesCounter = 0;
    data.forEach((byte) {
      if (byte == 8 || byte == 127) {
        backspacesCounter++;
      }
    });
    Uint8List buffer = Uint8List(data.length - backspacesCounter);
    int bufferIndex = buffer.length;

    // Apply backspace control character
    backspacesCounter = 0;
    for (int i = data.length - 1; i >= 0; i--) {
      if (data[i] == 8 || data[i] == 127) {
        backspacesCounter++;
      } else {
        if (backspacesCounter > 0) {
          backspacesCounter--;
        } else {
          buffer[--bufferIndex] = data[i];
        }
      }
    }

    // Create message if there is new line character
    String dataString = String.fromCharCodes(buffer);
    int index = buffer.indexOf(13);
    if (~index != 0) {
      setState(() {
        // messages.add(
        //   _Message(
        //     1,
        //     backspacesCounter > 0
        //         ? _messageBuffer.substring(
        //             0, _messageBuffer.length - backspacesCounter)
        //         : _messageBuffer + dataString.substring(0, index),
        //   ),
        // );
        _messageBuffer = dataString.substring(index);
      });
    } else {
      _messageBuffer = (backspacesCounter > 0
          ? _messageBuffer.substring(
              0, _messageBuffer.length - backspacesCounter)
          : _messageBuffer + dataString);
    }

    print('接收到的消息$_messageBuffer');
  }

//漆膜仪连接
  connect() async {
//     flutterBlue.connectedDevices.then((value) {
//             /// 逻辑
//             ///
//             print('已连接设备$value');
//  });
    //  Future<List<BluetoothDevice>> devices = flutterBlue.connectedDevices;

    // //  for(int i =0;i<devices.length;i++){

    // //  }
    //  print('连接的设备列表$devices');
    // SystemSetting.goto(SettingTarget.BLUETOOTH);
    // LoadingPage loadpage = new LoadingPage(context);
    // loadpage.show();
    //flutterBlue.startScan();

    // flutterBlue.scan(scanMode: ScanMode.lowLatency).listen((scanresult) {
    //   print(scanresult.device);
    //   print('蓝牙名称' + scanresult.device.name);
    //   print('蓝牙名称12121' + scanresult.advertisementData.localName);

    //   String deveceName = scanresult.advertisementData.localName;
    //   String deviceId = scanresult.device.id.toString();
    //   if (startscan == false) {
    //     formList = [];
    //     devices = [];
    //   }
    //   var item = {'name': deviceId, 'value': ''};
    //   formList.add(item);
    //   devices.add(scanresult.device);
    //   setState(() {
    //     formList = formList;
    //     devices = devices;
    //   });
    //   if (deveceName.startsWith('OBD')) {
    //     flutterBlue.stopScan();
    //   }
    // if (deveceName.startsWith('OBD')) {
    //   // loadpage.close();
    //   Future.delayed(Duration(seconds: 0), () {});

    //   device = scanresult.device;

    //   flutterBlue.stopScan();
    // } else {
    //   //Toast.show('正在重新扫描设备', context);
    // }
    //});
    flutterBlue.startDiscovery().listen((r) {
      print('扫描到设备');
      print(r.device.name);
      if (r.device.name != null) {
        if (startscan == false) {
          formList = [];
          devices = [];
        }
        var item = {'name': r.device.name, 'value': ''};
        formList.add(item);
        devices.add(r.device);
        setState(() {
          formList = formList;
          devices = devices;
        });
      }
      if (r.device.name != null && r.device.name.startsWith('OBD')) {
        print('找到目标设备');
        flutterBlue.cancelDiscovery(); //停止扫描

      }
    });
  }

  //}

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return new Scaffold(
      appBar: new AppBar(
        title: new Text('蓝牙'),
        backgroundColor: Colors.white,
        elevation: 0,
      ),
      floatingActionButtonLocation: FloatingActionButtonLocation.endFloat,
      floatingActionButton: FloatingActionButton(
        onPressed: () async {
          //connect();
          //change();
          if (startscan == false) {
            connect();
            setState(() {
              startscan = true;
            });
          } else {
            // sendCode = "ATZ";
            // writedata(sendCode);
            flutterBlue.cancelDiscovery();
            if (device.isBonded) {
              await flutterBlue.removeDeviceBondWithAddress(device.address);
            }

            setState(() {
              startscan = false;
            });
          }
        },
        child: Icon(
          Icons.add,
          color: Colors.white,
        ),
        backgroundColor: Color.fromRGBO(27, 182, 251, 1),
      ),
      body: new ListView(
        children: <Widget>[buildcontent()],
      ),
    );
  }
}
